package com.linln.common.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * @author : pengliang
 * @version V1.0
 * @Project: timo
 * @Package com.linln.common.utils
 * @Descriptio /**
 * @Project: timo
 * @Package com.linln.common.utils
 * @Description: 获取位置信息
 * @date Date : 2020年12月02日 14:21
 */
public class GeoUtil {


    //通过经度纬度获取地区信息    百度api
    public static String getCityByAddress(String lon, String lat) {
        String address = "";
        try {
            URL url = new URL("http://api.map.baidu.com/reverse_geocoding/v3/?ak=kiaTfcnZZhDN3DxDpOdfHvi89rPt4HoQ&output=json&coordtype=wgs84ll&location=" + lat + "," + lon);
            HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
            ucon.connect();
            InputStream in = ucon.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            String str = reader.readLine();
            //outprint.print(str);
//            str = str.substring(str.indexOf("(") + 1, str.length()-1);
            System.out.println(str);
            JSONObject jsonObject = (JSONObject) JSONObject.parseObject(str).get("result");
            JSONObject addressComponent = (JSONObject) jsonObject.get("addressComponent");
            address = (String) addressComponent.get("city");
            //outprint.print(str);
//            JSONObject jsonObject = JSONObject.fromObject(str);
//            address = jsonObject.getJSONObject("result").getString("addressComponent");
//            jsonObject = JSONObject.fromObject(address);
//            address=jsonObject.getString("city");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return address;
    }


    //通过经度纬度获取地区信息    腾讯api
    public static net.sf.json.JSONObject getLatAndLng(String lat, String lng) {
        try {
            String key = "ITLBZ-DYMWD-LW344-PHN4R-G2JT6-2SFWR";
//            String sin = MD5Util.md5Encode("/ws/geocoder/v1?key="+key+"&location="+lat+","+lng+"Ja1H8DwKgBTDat696WNnof1DGZI8KSh5","utf-8");
//            String hsUrl = "https://apis.map.qq.com/ws/geocoder/v1/?location="+lat+","+lng+"&key="+key+"&sig="+sin+"&get_poi=1";
            String hsUrl = "https://apis.map.qq.com/ws/geocoder/v1/?location=" + lng + "," + lat + "&key=" + key + "&get_poi=1";

            URL url;

            url = new URL(hsUrl);
            HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
            con.setRequestMethod("GET");// 提交模式
            X509TrustManager xtm = new X509TrustManager() {
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    // TODO Auto-generated method stub
                    return null;
                }

                @Override
                public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                        throws CertificateException {
                    // TODO Auto-generated method stub

                }

                @Override
                public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                        throws CertificateException {
                    // TODO Auto-generated method stub

                }
            };

            TrustManager[] tm = {xtm};

            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, tm, null);

            con.setSSLSocketFactory(ctx.getSocketFactory());
            con.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }
            });


            InputStream inStream = con.getInputStream();
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            byte[] b = outStream.toByteArray();//网页的二进制数据
            outStream.close();
            inStream.close();
            String rtn = new String(b, "utf-8");
            if (StringUtils.isNotBlank(rtn)) {
                net.sf.json.JSONObject object = net.sf.json.JSONObject.fromObject(rtn);
                if (object != null) {
                    if (object.has("status") && object.getInt("status") == 0) {
                        net.sf.json.JSONObject result = net.sf.json.JSONObject.fromObject(object.get("result"));
                        if (result != null) {
//                            net.sf.json.JSONObject addressComponent = net.sf.json.JSONObject.fromObject(result.get("address_component"));
//                            if (addressComponent != null) {
//                                return addressComponent.getString("city");
//                            }
                            return result;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
//        getCityByAddress("115.993344", "28.674697");
//        System.out.println("");
        System.out.println(getLatAndLng("28.674697", "116.01587940049476"));
    }
}
